package org.nanhill.moo.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nanhill.commons.pattern.domain.DomainNotFoundException;
import org.nanhill.moo.domain.User;
import org.nanhill.moo.service.UserService;
import org.nanhill.moo.web.UserSession;
import org.nanhill.moo.web.form.LoginForm;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

/**
 * @author alin
 */
public class LoginController extends SimpleFormController {
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public LoginController() {
		setCommandClass(LoginForm.class);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		LoginForm form = (LoginForm) command;
		User login;
		try {
			login = userService.logon(form.getEmail(), form.getPassword());
		} catch (DomainNotFoundException e) {
			errors.rejectValue("email", "errors.notfound", null, null);
			return this.showForm(request, response, errors);
		}
		UserSession.initUserSession(login, request);
		return new ModelAndView(this.getSuccessView());
	}
}